package com.together.sfipp.controller;

import com.together.sfipp.pojo.Baby;
import com.together.sfipp.pojo.Result;
import com.together.sfipp.service.BabyService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/baby")
public class BabyController {
    @Resource
    private BabyService babyService;

    // 从配置文件读取存储路径和访问前缀
    @Value("${file.upload.image-path}")
    private String imagePath;

    @Value("${file.upload.image-url-prefix}")
    private String imageUrlPrefix;

    //添加育儿信息
    @PostMapping("/insert")
    public Result insert(@RequestBody Baby baby){
        Integer amount = babyService.selectAmount("育儿补贴");
        baby.setBabyAmount(amount * baby.getBabyNumber());
        baby.setBabyStatus("待审核");
        babyService.insert(baby);
        return Result.success("添加成功");
    }

    //删除育儿信息
    @DeleteMapping("/delete")
    public Result delete(Integer babyId){
        babyService.delete(babyId);
        return Result.success("删除成功");
    }

    //修改育儿信息
    @PutMapping("/update")
    public Result update(@RequestBody Baby baby){
        if(baby.getBabyNumber() != null){
            Integer amount = babyService.selectAmount("育儿补贴");
            baby.setBabyAmount(amount * baby.getBabyNumber());
        }
        babyService.update(baby);
        return Result.success("修改成功");
    }

    //查询育儿信息
    @GetMapping("/selectAll")
    public Result<List<Baby>> selectAll(){
        List<Baby> b = babyService.selectAll();
        return Result.success(b);
    }

    //查询所需信息
    @GetMapping("/selectNeed")
    public Result<List<Baby>> selectNeed(@RequestParam Map<String, Object> params){
        List<Baby> b = babyService.selectNeed(params);
        return Result.success(b);
    }

    // 图片上传接口
    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        // 校验文件类型（仅允许图片格式）
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        if (!suffixName.matches("\\.(jpg|jpeg|png|gif)$")) {
            throw new RuntimeException("仅支持jpg、jpeg、png、gif格式的图片");
        }

        // 生成唯一文件名
        fileName = UUID.randomUUID() + suffixName;

        // 创建存储目录（自动创建多级目录）
        File dir = new File(imagePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 保存文件到本地
        File destFile = new File(imagePath + fileName);
        file.transferTo(destFile);

        // 返回可访问的图片URL
        return imageUrlPrefix + fileName;
    }
}
